<template>
    <div>
        <a-modal v-model:visible="modalVisible" title="定时关机" @ok="handleOk" :confirm-loading="confirmLoading">
            <div class="instance-modal">
                <a-form :model="form">
                    <a-form-item label="定时时间">
                        <a-date-picker v-model:value="form.shutDownTime" :disabled-date="disabledDate" show-time
                            :disabledTime="disabledDateTime" @change="onChangeTime" />
                        <a-button v-if="cancleshutDown" @click="handleCancel" type="link" class="ml-8">清除</a-button>
                    </a-form-item>
                    <a-form-item label="预估费用" class="mb-16">
                        <span class="col-money">￥ {{ estimatedCost }}</span>
                    </a-form-item>
                    <a-form-item label="账户余额" class="mb-16">
                        <span class="col-money">￥ {{ accountInfo.balance }}</span>
                    </a-form-item>

                    <div class="fz-14 col-223354"> <svg-icon name="icon_info" style="width:14px;height:14px;margin-right: 4px;color: #F5222D;" />编辑后将<span class="col-warn">覆盖</span>原定时关机设置，清除则取消  </div>
                </a-form>
            </div>
        </a-modal>
    </div>
</template>

<script setup>
import { defineProps, defineEmits, computed, ref } from 'vue';
import { handleInstance } from 'api/modules/api.instance'
import dayjs from "dayjs"
import { storeToRefs } from 'pinia'
import userInfoStore from '@/stores/userInfo.js'
const useUserInfoStore = userInfoStore()
const { accountInfo } = storeToRefs(useUserInfoStore);

const props = defineProps({
    modelValue: {
        type: Boolean,
    },
    instance: {
        type: Object,
        default: {}
    }
});

// 获取实例单价
const instance_price = ref('')
const getInstancePrice = () => {
    instance_price.value = props.instance?.Order?.price
}

getInstancePrice()

// 计算预估费用
const estimatedCost = ref('')
const onChangeTime = (e) => {
    const minute = dayjs(form.value.shutDownTime).diff(dayjs(props.instance?.Instance?.lastOrderTime), 'minute')  // 计算的是按量付费的分钟
    const discount = accountInfo.value?.userDiscount?.instanceDiscount || 1
    estimatedCost.value = ((minute / 60) * instance_price.value * discount).toFixed(2)
}


const form = ref({})
const cancleshutDown = ref(false)
if (props?.instance?.Instance?.scheduleStopTime) {
    cancleshutDown.value = true
    form.value.shutDownTime = dayjs(props?.instance?.Instance?.scheduleStopTime)
    onChangeTime()
}

const handleCancel = () => {
    form.value.shutDownTime = null
}

const range = (start, end) => {
    const result = []
    for (let i = start; i < end; i++) {
        result.push(i)
    }
    return result
}


const disabledDate = (current) => {
    return current && current < dayjs().subtract(1, 'day').endOf('day')
}

const disabledDateTime = (dates) => {
    const hours = dayjs().hour()
    const minutes = dayjs().minute()
    const seconds = dayjs().second()
    if (!dates) {
        dates = dayjs()
    }
    // 当日只能选择当前时间之后的时间点 如果不需要限制秒的话 将disabledSeconds所有行注释了就行
    // console.log(dates, dayjs(dates).date(), dayjs().date())
    if (dates && dayjs(dates).date() === dayjs().date()) {
        if (dayjs(dates).hour() === dayjs().hour()) {
            return {
                disabledHours: () => range(0, hours),
                disabledMinutes: () => range(0, minutes),
                disabledSeconds: () => range(0, seconds),
            }
        } else {
            return {
                disabledHours: () => range(0, hours),
                disabledMinutes: () => [],
                disabledSeconds: () => [],
            }
        }
    } else {
        return {
            disabledHours: () => [],
            disabledMinutes: () => [],
            disabledSeconds: () => [],
        }
    }
}

const emit = defineEmits(['update:modelValue', 'handelOpt', 'handelNoBalance']);
const modalVisible = computed({
    get: () => props.modelValue,
    set: v => emit('update:modelValue', v),
});

// 确定按钮的回调
const confirmLoading = ref(false)
const handleOk = () => {
    const params = {
        instanceId: props.instance?.Instance?.instanceId,
        method: 'setting',
        subject: 'schedule_stop',
        shutDownTime: form.value.shutDownTime
    }
    confirmLoading.value = true
    handleInstance(params).then((res) => {
        confirmLoading.value = false
        if (res.code == 0) {
            emit('update:modelValue', false)
            emit('handelOpt', props.instance?.Instance?.instanceId)
            cancleshutDown.value = false
        }
    }).catch(err => {
        confirmLoading.value = false
        if (err.code == 10111) {
            emit('update:modelValue', false)
            emit('handelNoBalance', estimatedCost.value)
            cancleshutDown.value = false
        }
    })
};

</script>

<style scoped lang="less">
.instance-modal {
    font-size: 14px;
    color: #646F87;

    &>div {
        margin-bottom: 8px;
    }
}
</style>


